// pages/mystore/category/index.js
import { apiUrls, makeRequest } from '../../../utils/api';

const App = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    categoryItems: [],
    categoryIndex: 0,
    category_id: 3,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    that.setData({
      id: options.id
    })
    that.wxValidate = App.wxValidate(
      {
        category_id: {
          required: true
        },

      }
      , {
        category_id: {
          required: '请填写选择分类'
        },
      }
    );
    makeRequest({
      url: apiUrls.getCategories,
      method: 'GET',
      success: function (res) {
        that.setData({
          categoryItems: res.data.data
        });
      }
    });
    makeRequest({
      url: apiUrls.getShopDetail(options.id),
      method: 'GET',
      data: {
        include: 'category,manager,area'
      },
      success: function (res) {
        let categoryIndex = that.data.categoryItems.findIndex(function (x) {
          return x.id == res.data.data.category_id;
        });
        console.log(categoryIndex)
        that.setData({
          category_id: res.data.data.category_id,
          categoryIndex: categoryIndex
        })
      }
    });

  },
  bindSubmit(e) {
    let that = this;
    //提交错误描述
    if (!this.wxValidate.checkForm(e)) {
      const error = this.wxValidate.errorList[0]
      // `${error.param} : ${error.msg} `
      wx.showToast({
        title: `${error.msg} `,
        image: '/images/error.png',
        duration: 500
      })
      return false
    }
    else {
      makeRequest({
        url: apiUrls.putCategoryEdit(that.data.id),
        method: 'PUT',
        data: e.detail.value,
        success: function (res) {
          console.log(res);
          if (res.statusCode === 422) {
            wx.showToast({
              title: `${res.data.data[Object.keys(res.data.data)[0]][0]} `,
              image: '/images/error.png',
              duration: 500
            })
          } else if (res.statusCode === 200) {
            wx.showToast({
              title: '保存成功',
              duration: 2000,
              success: function () {
                setTimeout(function () {
                  wx.navigateBack({
                    delta: 1
                  });
                }, 1000);
              }
            });
          }
        }
      });
    }
    //console.log(e.detail.value)
  },
  /**
     * 分类选择绑定
     */
  bindCategoryPickerChange: function (e) {
    console.log(e);
    const that = this;
    const index = e.detail.value;
    const vId = this.data.categoryItems[index].id;
    that.setData({
      categoryIndex: index,
      category_id: vId
    });
  },
})